/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

export function observe(obj: any, callback: () => void) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  Object.keys(obj).forEach((key) => {
    const internalValue = obj[key];
    if (typeof internalValue === 'object') {
      obj[key] = createObservableObject(internalValue, callback);
    }
  });
  return createObservableObject(obj, callback);
}

function createObservableObject(obj: any, callback: () => void) {
  return new Proxy(obj, {
    set: function (target: any, prop: string | symbol, newValue: any) {
      target[prop] = newValue;
      callback();
      return true;
    },
  });
}
